package pers.crayon.baseprogram.sign;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import pers.crayon.baseprogram.sign.tools.MD5Signature;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 使用MD5算法进行签名
 */
@Slf4j
public class MD5Signer implements HttpSigner {
    private String privateKey;
    private String publicKey;

    public MD5Signer(String privateKey, String publicKey) {
        this.privateKey = privateKey;
        this.publicKey = publicKey;
    }

    /**
     * 获取MD5签名实例
     *
     * @param privateKey the private key
     * @return instance
     */
    public static MD5Signer getInstance(String privateKey, String publicKey) {
        return new MD5Signer(privateKey, publicKey);
    }

    /**
     * 请求串加签
     * <p>
     * MD5 可以按照指定字段顺序加密JSON
     *
     * @param request the request
     * @return string
     * @throws Exception the exception
     */
    @Override
    public String doSign(String request) throws Exception {
        //组装加密串
        String signContent = JSON.toJSONString(request);
        // 一些组装操作
        //sign
        String sign = MD5Signature.sign(signContent, privateKey);
        log.debug("[COIN_MD5_SDK_SIGN]-============签名:{}", sign);
        return sign;
    }

    /**
     * 验签名
     *
     * @param content the content
     * @return boolean
     */
    @Override
    public boolean doVerify(String content) {
        log.debug("[COIN_MD5_SDK_VERIFY]-content:{}", content);
        HashMap<String, Object> result = JSONUtil.toBean(content, LinkedHashMap.class);
        String signResult = result.get("sign").toString();
        result.remove("sign");
        log.debug("[COIN_MD5_SDK_VERIFY]-signResult:{}", signResult);
        return doVerify(result, signResult);
    }

    /**
     * Do verify boolean.
     *
     * @param result     the result
     * @param signResult the sign result
     * @return the boolean
     */
    @Override
    public boolean doVerify(HashMap<String, Object> result, String signResult) {
        String resultStr = JSON.toJSONString(result);
        log.debug("[COIN_MD5_SDK_VERIFY]-result:{}", resultStr);
        boolean ret = MD5Signature.doCheck(resultStr, signResult, this.publicKey);
        log.debug("[COIN_MD5_SDK_VERIFY]-ret:{}", ret);
        return ret;
    }
}
